package com.netease.xone.fragment;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.meta.AppInfo;
import protocol.meta.LoopBack;
import Utils.StackTraceUtil;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.handmark.pulltorefresh.library.X1LoadingAdapterViewBase.OnLoadingListener;
import com.netease.log.NTLog;
import com.netease.pkgRelated.XoneConsts;
import com.netease.pkgRelated.XoneConsts.INFO_GROUP;
import com.netease.pkgRelated.XoneConsts.MENU_ID;
import com.netease.pkgRelated.XoneConsts.SORT_TYPE;
import com.netease.xone.R;
import com.netease.xone.activity.ActivityDiscuss;
import com.netease.xone.activity.ActivityInfoDetail;
import com.netease.xone.adapter.AdapterInfo;
import com.netease.xone.app.XoneApp;
import com.netease.xone.dataMgr.ParcelableArgument;
import com.netease.xone.view.MainTitlePopupWindow1;
import com.netease.xone.widget.appmsg.AppMsg;
import com.netease.xone.widget.listview.LoadingListView;
import com.netease.xone.widget.tabview.MainTab;

import db.XoneDBTables.AppInfoTable;
import db.manager.ManagerAccount;
import db.manager.ManagerAppInfo;


public class FragmentInfo extends FragmentAudioBase implements IFragmentMain, OnClickListener,
    OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> {

    public static final String TAG = FragmentInfo.class.getSimpleName();
    public static final int DELAY_TIME = 1000;
    
    private int mLoadId = TAG.hashCode();
    
    /**
     * Fragment是否可见
     */
    private boolean isVisibleToUser = false;
    /**
     * 加载数据标志
     */
    private boolean bLoadData = false;
    /**
     * 首页导航选中位置
     */
    private int mMainSelectedIndex = 0;
    
    private int mInfoGroup = 0;
    private int mSortType = 1;
    
    private LinkedList<Integer> mReqList = new LinkedList<Integer>();
    
    private List<String> mMainTitleList;
    
    // 当前分类资讯id
    private List<String> mListIds;
    // 存放分类资讯id，用来比较得出是否有新资讯
    private SparseArray<List<String>> mArrayList = new SparseArray<List<String>>();
    private AdapterInfo mAdapter;
    
    private View mRootView;
    private LoadingListView mListView;
    private ActionBar mActionBar;
    private AppMsg mAppMsg;
    
    public static FragmentInfo newInstance(Parcelable obj) {
        FragmentInfo f = new FragmentInfo();
        Bundle b = new Bundle();
        b.putParcelable("obj", obj);
        f.setArguments(b);
        return f;
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        NTLog.d(TAG, StackTraceUtil.getMethodName()
                + " savedInstanceState=" + (null == savedInstanceState ? "null" : savedInstanceState.toString()));
        super.onCreate(savedInstanceState);
        bLoadData = false;
        setHasOptionsMenu(true);
        mActionBar = getSherlockActivity().getSupportActionBar();
        XoneService.getInstance().addListener(mXoneCallBack);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        NTLog.d(TAG, StackTraceUtil.getMethodName()
                + " savedInstanceState=" + (null == savedInstanceState ? "null" : savedInstanceState.toString()));
        mRootView = inflater.inflate(R.layout.fragment_info, container, false);
        findViews(mRootView);
        
        if (null == savedInstanceState) {
            mListView.load();
        } else {
            mMainSelectedIndex = savedInstanceState.getInt("select", 0);
        }
        return mRootView;
    }
    
    @Override
    public void onResume() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        super.onResume();
        if (!bLoadData) {
            mListView.load();
        }
    }
    
    private void findViews(View root) {
        mListView = (LoadingListView)root.findViewById(R.id.listview);
        mListView.setOnItemClickListener(this);
        mListView.setOnLoadingListener(new OnLoadingListener(){

            @Override
            public void onRefreshing() {
                NTLog.d(TAG, StackTraceUtil.getMethodName());
                GetInfoIds();
                GetInfoList();
                // 在时间排序和按热度排序时状态时去除新资讯消息显示
                if (0 == mMainSelectedIndex 
                        || 1 == mMainSelectedIndex) {
                    MainTab.hideMsg(MainTab.INDEX_NEWS);
                }
            }

            @Override
            public void onLoading() {
                NTLog.d(TAG, StackTraceUtil.getMethodName());
                // 在时间排序和按热度排序时状态时去除新资讯消息显示
                if (0 == mMainSelectedIndex 
                        || 1 == mMainSelectedIndex) {
                    MainTab.hideMsg(MainTab.INDEX_NEWS);
                }
                loadData(null);
            }

            @Override
            public void onLoadingMore() {
                NTLog.d(TAG, StackTraceUtil.getMethodName());
                GetInfoList();
            }
            
        });
        
    }

    private void loadData(Object obj) {
        NTLog.d(TAG, StackTraceUtil.getMethodName() + " obj=" + (null == obj ? "null" : obj.toString()));
        bLoadData = true;
        
        if (null == obj) {
            if (null == mAdapter) {
                mAdapter = new AdapterInfo(getSherlockActivity(), null);
            }
            
            getSherlockActivity().getSupportLoaderManager().restartLoader(mLoadId, null, this).forceLoad();
        }else if (null != obj && obj instanceof AdapterInfo) {
            mAdapter = (AdapterInfo)obj; 
        } 
        mListView.setAdapter(mAdapter);
    }

    private void GetInfoIds() {
        int id = XoneService.getInstance().doGetInfoIds(mInfoGroup, mSortType, XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT);
        mReqList.add(id);
    }
    
    private void GetInfoList() {
        if (null == mAdapter || null == mListIds) {
            return;
        }
        
        final int count = mAdapter.getCount();
        final int size = mListIds.size();
        if (count >= size) {
            return;
        }
        int end = count+XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT;
        if (count+XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT >= size) {
            end = size;
        }
        
        List<String> list = mListIds.subList(count, end);
        int len = list.size();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < len; i++) {
            if (i == len-1) {
                builder.append(list.get(i));
            } else {
                builder.append(list.get(i)).append(",");
            }
        }
        
        int id = XoneService.getInstance().doGetInfoList(false, mInfoGroup, mSortType, builder.toString());
        mReqList.add(id);
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        super.onCreateOptionsMenu(menu, inflater);
        MenuItem item = null;
        
        item = menu.add(Menu.NONE, MENU_ID.menu_info_discuss, 0, "discuss");
        item.setIcon(R.drawable.icon_action_write_selector);
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        switch (item.getItemId()) {
            case android.R.id.home:
                break;
            case MENU_ID.menu_info_discuss:
                if (XoneApp.getAppInstance().isLoginUser(getActivity())) {
                    ParcelableArgument arg = new ParcelableArgument(ParcelableArgument.TYPE_DEFAULT);
                    ActivityDiscuss.launch(getActivity(), arg);
                }
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }
    
    @Override
    public void onRestoreCustomNonConfigurationInstance(Object obj) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        loadData(obj);
    }
    
    @Override
    public Object onRetainCustomNonConfigurationInstance() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        return mAdapter;
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        super.onSaveInstanceState(outState);
        outState.putInt("select", mMainSelectedIndex);
    }
    
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        NTLog.d(TAG, StackTraceUtil.getMethodName() + "isVisibleToUser=" + isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        if (!isVisibleToUser) {
            if (null != mAppMsg) {
                mAppMsg.cancel();
            }
        }
        super.setUserVisibleHint(isVisibleToUser);
    }
    
    @Override
    public void onDestroyView() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        super.onDestroyView();
        if (null != mAdapter) {
            mAdapter.clear();
        }
    }
    
    @Override
    public void onDestroy() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        super.onDestroy();
       
        XoneService.getInstance().removeListener(mXoneCallBack);
        mReqList.clear();
        mAdapter = null;
        mXoneCallBack = null;
        mMainTitleList = null;
        mRootView = null;
        mActionBar = null;
        if (null != mAppMsg) {
            mAppMsg.cancel();
        }
        mAppMsg = null;
        mHandler.removeCallbacks(mRunnable);
        mHandler = null;
        mRunnable = null;
    }
    
    @Override
    public void onClick(View v) {
        final int id = v.getId();
        NTLog.d(TAG, StackTraceUtil.getMethodName() + " id=" + id);
        switch (id) {
            case R.id.custom_title:
                // 根据是否登陆用户来生成不同的导航菜单
                if (ManagerAccount.getInstance().isNormalLoginUser()) {
                    mMainTitleList = Arrays.asList((getResources().getStringArray(R.array.main_custom_title)));
                } else {
                    mMainTitleList = Arrays.asList((getResources().getStringArray(R.array.main_custom_user_title)));
                }
                new MainTitlePopupWindow1(getActivity(), 
                        mActionBar, 
                        this,
                        mMainTitleList, 
                        mMainSelectedIndex);
                break;
            default:
                if (id != mMainSelectedIndex) {
                    setMainTitle(id);
                }
                mListView.reLoad();
                break;
        }
    }
    
    @Override
    public void onPageSelected(int index) {
        NTLog.d(TAG, StackTraceUtil.getMethodName() + " index=" + index);
        if (null == mActionBar.getCustomView()) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_main_custom_title,
                    null);
            view.setOnClickListener(this);
            ActionBar.LayoutParams params = new ActionBar.LayoutParams(
                    ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.MATCH_PARENT,
                    Gravity.LEFT);
            mActionBar.setCustomView(view, params);
            setMainTitle(mMainSelectedIndex);
        }
        mActionBar.setDisplayShowTitleEnabled(false);
        mActionBar.setDisplayShowCustomEnabled(true);
    }
    
    @Override
    public void onPageReSelected(int index) {
        mListView.reLoad();
    }
    
    private void setMainTitle(int index) {
        mMainSelectedIndex = index;
        
        mInfoGroup = 0;
        mSortType = -1;
        switch (mMainSelectedIndex) {
            case MainTitlePopupWindow1.MENU_TIME:
                mInfoGroup = INFO_GROUP.ALL;
                mSortType = SORT_TYPE.TIME;
                break;
            case MainTitlePopupWindow1.MENU_TOPIC:
                mInfoGroup = INFO_GROUP.ALL;
                mSortType = SORT_TYPE.TOPIC;
                break;
            case MainTitlePopupWindow1.MENU_MY_SUBSCRIBE:
                mInfoGroup = INFO_GROUP.SUBSCRIBE;
                break;
            case MainTitlePopupWindow1.MENU_MY_FOLLOW:
                mInfoGroup = INFO_GROUP.FOLLOW;
                break;
            case MainTitlePopupWindow1.MENU_MY_DISCUSS:
                mInfoGroup = INFO_GROUP.DISCUSS;
                break;
            default:
                break;
        }
        
        if (0 == mMainSelectedIndex 
                || 1 == mMainSelectedIndex) {
            // 当选择按时间排序和按热度排序时，都显示全部资讯
            ((TextView)mActionBar.getCustomView().findViewById(R.id.textview1)).setText(R.string.actionbar_item);
        } else {
            ((TextView)mActionBar.getCustomView().findViewById(R.id.textview1)).setText(mMainTitleList.get(mMainSelectedIndex));
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        String infoId = null;
        Object obj = parent.getAdapter().getItem(position);
        if (obj instanceof AppInfo) {
            infoId = ((AppInfo)obj).getInfoId();
            if (TextUtils.isEmpty(infoId)) {
                return;
            }
        }
        
        ActivityInfoDetail.startActivity(getActivity().getApplicationContext(), infoId, ActivityInfoDetail.MODE_FROM_INFO);
    }
    
    @Override
    public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());

        GetInfoIds();
        
        StringBuilder where = new StringBuilder();
        where.append(AppInfoTable.C_INFOGROUP).append("=").append(mInfoGroup).append(" AND ")
                .append(AppInfoTable.C_SORTTYPE).append("=").append(mSortType).append(" AND ")
                .append(AppInfoTable.C_ACCOUNT).append("='")
                .append(ManagerAccount.getInstance().getCurrentAccountId()).append("'");
        return new CursorLoader(getActivity(), AppInfoTable.CONTENT_URI, ManagerAppInfo.Projection,
                where.toString(), null, null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        NTLog.d(TAG, StackTraceUtil.getMethodName() + " cursor.getCount()=" + cursor.getCount());
        if (null != mAdapter && null != cursor) {
            mAdapter.swapCursor(cursor);
        }
        
        if (null != mListIds) {
            if (cursor.getCount() >= mListIds.size()) {
                mListView.onLoadingComplete(false);
            } else {
                mListView.onLoadingComplete(true);
            }
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
    }
    
    private Handler mHandler = new Handler();
    private Runnable mRunnable = new Runnable() {

        @Override
        public void run() {
            // 切换帐号时清空原来所有保持的分类id
            mArrayList.clear();
            mListView.reLoad();
        }
        
    };
    
    private XoneCallBack mXoneCallBack = new XoneCallBack() {
        
        @Override
        public void onGetInfoIds(int transactionId, Object obj) {
            if (mReqList.remove(Integer.valueOf(transactionId))) {
                String[] infoIds = null;
                if (obj instanceof String[]) {
                    infoIds = (String[])obj;
                    mListIds = Arrays.asList(infoIds);
                }
                NTLog.d(TAG, StackTraceUtil.getMethodName() + " mListIds.size=" + mListIds.size() 
                        + " mAdapter.getCount()=" + mAdapter.getCount());
                mListView.onRefreshComplete();
                
                // 比较新老id，得到新的资讯数
                if (null != mArrayList.get(mMainSelectedIndex) && isVisibleToUser) {
                    int count = 0;
                    List<String> oldListIds = mArrayList.get(mMainSelectedIndex);
                    for (String ids : mListIds) {
                        if (!oldListIds.contains(ids)) {
                            count++;
                        }
                    }
                    
                    String value = null;
                    if (0 == count) {
                        value = getString(R.string.info_unread_no);
                    } else {
                        value = getString(R.string.info_unread_count, count);
                    }
                    
                    mAppMsg = AppMsg.makeText(getActivity(), value, AppMsg.STYLE_INFO);
                    mAppMsg.show();
                }
                
                mArrayList.put(mMainSelectedIndex, mListIds);
            } else {
                
            }
        };
        
        @Override
        public void onGetInfoIdsError(int transactionId, int errCode, String err) {
            if (mReqList.remove(Integer.valueOf(transactionId))) {
                mListView.onLoadingComplete(false);
                mListView.onRefreshComplete();
            } else {

            }
        };
        
        @Override
        public void onGetInfoList(int transactionId, Object obj) {
            if (mReqList.remove(Integer.valueOf(transactionId))) {
                NTLog.d(TAG, StackTraceUtil.getMethodName() + " mListIds.size=" + mListIds.size() 
                        + " mAdapter.getCount()=" + mAdapter.getCount());
            } else {
                
            }
        };
        
        @Override
        public void onGetInfoListError(int transactionId, int errCode, String err) {
            if (mReqList.remove(Integer.valueOf(transactionId))) {
                mListView.onLoadingMoreComplete(false);
            } else {
                
            }
        };
        
        /**
         * 显示讨论发送的消息
         */
        @Override
        public void onLoopBack(int transactionId, Object obj) {
            if (null == obj) {
                return;
            }
            
            if (obj instanceof LoopBack) {
                LoopBack lb = (LoopBack)obj;
                if (lb.mType == FragmentDiscuss.TAG.hashCode()) {
                    if (isVisibleToUser) {
                        mAppMsg = AppMsg.makeText(getActivity(), (String)lb.mData, AppMsg.STYLE_INFO);
                        mAppMsg.show();
                    }
                } else if(lb.mType == XoneConsts.LOOPBACK_TYPE.switch_account){
                    if(lb.mData != null && lb.mData instanceof Boolean){
                        boolean flag = (Boolean)lb.mData;
                        if (flag) {
                            mHandler.removeCallbacks(mRunnable);
                            mHandler.postDelayed(mRunnable, DELAY_TIME);
                        } else {
                            
                        }
                    }

                }
            }
        };
    };
}
